import {Workbox} from 'workbox-window';
import {registerRoute} from 'workbox-routing';
import {NetworkFirst} from 'workbox-strategies';
import {equals} from "jsmethod-extra";
import {fetchInterceptorPlugin} from "../plugins";

/**
 * @author lihh
 * @description serviceWorker hooks
 */
export function useServiceWorker() {
    if ('serviceWorker' in navigator) {
        const wb = new Workbox('/sw.js');

        wb.register().then(function () {
            console.log("service worker install successful.")

            // 定义路由
            registerRoute(
                ({url}) => equals(url.pathname, "/"),
                // 这是网络 优先
                new NetworkFirst(
                    {
                        plugins: [fetchInterceptorPlugin()]
                    }
                )
            );
        });
    }

}
